﻿<#

    Credits: https://blogs.infosupport.com/managing-ssrs-reports-with-powershell/
#>
Function Export-SSRSObject($ssrsServerName,$sourcePathToExport,$recursive,$targetExportPath)
{
    Import-Module ..\BuildDeployment\libAssertion.psm1
    
    $reportServerUri = "http://$ssrsServerName/reportserver/ReportService2010.asmx?wsdl" 
 
    $rs = New-WebServiceProxy -Uri $reportServerUri -UseDefaultCredential  -Namespace "SSRS" 

    $items = $rs.ListChildren($sourcePathToExport, $recursive)

    Assert-Directory -path $targetExportPath
    
    
    $items | Where-Object { $_.TypeName -eq "Report" } | Foreach-Object { 

        $filename = ("{0}.rdl" -f $_.Name) 
        $reportDirectory=($targetExportPath + $_.Path.Substring(0,$_.Path.LastIndexOf("/")).Replace("/","\")).Replace("\\","\")

        if($reportDirectory -like "*QA2_Forms*")
        {
            $break=$true
        }
        Assert-Directory -path $reportDirectory
        Write-Output ("Downloading ""{0}""..." -f $_.Path) 
        $bytes = $rs.GetItemDefinition($_.Path) 
        [System.IO.File]::WriteAllBytes("$reportDirectory\$filename", $bytes) 
        } 

    $items | Where-Object { $_.TypeName -eq "DataSource" } | Foreach-Object { 

        $filename = ("{0}.rds" -f $_.Name) 
        $reportDirectory=($targetExportPath + $_.Path.Substring(0,$_.Path.LastIndexOf("/")).Replace("/","\")).Replace("\\","\")
        Assert-Directory -path $reportDirectory
        Write-Output ("Downloading ""{0}""..." -f $_.Path) 
        $bytes = $rs.GetItemDefinition($_.Path) 
        [System.IO.File]::WriteAllBytes("$reportDirectory\$filename", $bytes) 
        } 

}

<#

    Credits: https://blogs.infosupport.com/managing-ssrs-reports-with-powershell/
#>
Function Import-SSRSObject($ssrsServerName,$sourcePathToImport,$targetImportPathRoot,$itemType,$overwriteObject,$outputWarnings)
{
    $reportServerUri = "http://$ssrsServerName/reportserver/ReportService2010.asmx?wsdl" 
 
    $rs = New-WebServiceProxy -Uri $reportServerUri -UseDefaultCredential  

    $proxyNamespace = $rs.GetType().Namespace

    if($itemType -eq "Report")
    {
        $fileFilter="*.rdl"
    }
    elseif($itemType -eq "DataSource")
    {
        $fileFilter="*.rds"    
    }
    elseif($itemType -eq "All")
    {
        $fileFilter="*.rd*"    
    }

    $objectsToImport=Get-ChildItem $fileFilter -Path $sourcePathToImport -Recurse

    $warnings = $null

    foreach($objectToImport in $objectsToImport)
    {
        
        $objectName = [System.IO.Path]::GetFileNameWithoutExtension($objectToImport.Name) 
        $bytes = [System.IO.File]::ReadAllBytes($objectToImport.FullName) 

        $targetImportPath=$targetImportPathRoot + $objectToImport.DirectoryName.Replace($sourcePathToImport,"").Replace("\","/")

        $directories=$objectToImport.DirectoryName.Replace($sourcePathToImport,"").Replace("\","/") -split "/" 

        for($i=1;$i -lt $directories.Count;$i++)
        {
            if($i -eq 1)
            {
                $parent=$targetImportPathRoot
            }
            else
            {
                $parent=$targetImportPathRoot
                for($j=1;$j -lt $i;$j++)
                {
                    $parent=$parent + "/" + $directories[$j]
                }
            }
            try
            {
                $rs.CreateFolder($directories[$i],$parent,$null)
            }
            catch
            {
                $ex=$_
                if($ex.Exception.Message  -ilike "*ItemAlreadyExistsException*")
                {
                    $message="Folder " + $parent + "/" + $directories[$i] + " already exists"
                    Write-Warning $message
                }
            }
        }
        
        if($objectToImport.Extension -eq ".rdl")
        {
            $itemType="Report"

            Write-Output "Uploading report ""$objectName"" to ""$targetImportPath""..."
            $report = $rs.CreateCatalogItem(
            $itemType,         # Catalog item type
            $objectName,      # Report name
            $targetImportPath,# Destination folder
            $overwriteObject,            # Overwrite report if it exists?
            $bytes,           # .rdl file contents
            $null,            # Properties to set.
            [ref]$warnings)   # Warnings that occured while uploading.
        }
        elseif($objectToImport.Extension -eq ".rds")
        {
            $itemType="DataSource"
            $dataSourceDefinition = New-Object ("$proxyNamespace.DataSourceDefinition")
            #$dataSourceDefinition = New-Object -TypeName SSRS.DataSourceDefinition

            [xml]$dataSourceXML = Get-Content $objectToImport.FullName -Encoding Unicode

            
            $dataSourceDefinition.Extension=$dataSourceXML.SelectNodes("/DataSourceDefinition/Extension").'#text'
            $dataSourceDefinition.ConnectString=$dataSourceXML.SelectNodes("/DataSourceDefinition/ConnectString").'#text'
            $dataSourceDefinition.UseOriginalConnectString=$dataSourceXML.SelectNodes("/DataSourceDefinition/UseOriginalConnectString").'#text'
            $dataSourceDefinition.OriginalConnectStringExpressionBased=$dataSourceXML.SelectNodes("/DataSourceDefinition/OriginalConnectStringExpressionBased").'#text'
            $dataSourceDefinition.CredentialRetrieval=$dataSourceXML.SelectNodes("/DataSourceDefinition/CredentialRetrieval").'#text'
            $dataSourceDefinition.WindowsCredentials=$dataSourceXML.SelectNodes("/DataSourceDefinition/WindowsCredentials").'#text'
            $dataSourceDefinition.ImpersonateUser=$dataSourceXML.SelectNodes("/DataSourceDefinition/ImpersonateUser").'#text'
            $dataSourceDefinition.UserName=$dataSourceXML.SelectNodes("/DataSourceDefinition/UserName").'#text'
            $dataSourceDefinition.Enabled=$dataSourceXML.SelectNodes("/DataSourceDefinition/Enabled").'#text'



            $rs.CreateDataSource($objectName,$targetImportPath,$overwriteObject,$dataSourceDefinition,$null)
        }

        


        if($outputWarnings)
        {
            $warnings | ForEach-Object { 
                    Write-Output ("Warning: {0}" -f $_.Message) 
                }
        }

    }
}